package org.roger.scorer;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.util.Bits;
import org.roger.util.DistanceUtil;

/**
 * 自定义分数（距离定义成分数）
 * @author luoweiyi
 */
public class DistanceScorer extends Scorer{
	
	protected final IndexReader reader;
	private int doc = -1;
	protected final int maxDoc;
	protected boolean checkDeletes;
	private final Bits liveDocs;

	public DistanceScorer(IndexReader reader) {
		super(null);
		this.reader = reader;
		this.maxDoc = reader.maxDoc();
		setCheckDeletes(true);
		this.liveDocs = MultiFields.getLiveDocs(reader);
	}

	@Override
	public float score() throws IOException {
		String location = reader.document(doc).get("location");
		if(location != null){
			int x = Integer.parseInt(location.split(",")[0]);
			int y = Integer.parseInt(location.split(",")[1]);
			return (float)DistanceUtil.getDistance(x, y);
		}
		return 0;
	}

	@Override
	public int freq() throws IOException {
		// TODO Auto-generated method stub
		return 1;
	}
	
	public void setCheckDeletes(boolean checkDeletes) {
	    this.checkDeletes = checkDeletes && reader.hasDeletions();
	}
	
	public boolean matches(int doc) {
	    return (!checkDeletes || liveDocs.get(doc)) && matchesValue(doc);
	}

	public boolean matchesValue(int doc) {
	  return true;
	}

	@Override
	public int docID() {
		 return doc;
	}

	@Override
	public int nextDoc() throws IOException {
		for (; ;) {
		   doc++;
		   if (doc >= maxDoc) return doc = NO_MORE_DOCS;
		   if (matches(doc)) return doc;
		}
	}

	@Override
	public int advance(int target) throws IOException {
		doc = target - 1;
	    return nextDoc();
	}

	@Override
	public long cost() {
		return maxDoc;
	}

}
